package com.github.icloudpay.pay.core.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* 
 * 利用HttpClient进行post请求的工具类 
 */  
public class HttpClientUtil {
	private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	public static String doPost(String url,String paramStr,String charset) throws Exception{
		logger.info("HTTP请求服务地址request url:"+url);
		HttpClient httpClient = null;  
		HttpPost httpPost = null;  
		String result = null;  
		httpClient = new SSLClient();  
		httpPost = new HttpPost(url);  
		//设置参数  
		logger.info("HTTP请求参数send request data:{}",paramStr);
		StringEntity entity = new StringEntity(paramStr,charset);//解决中文乱码问题 
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);
		/**请求发送成功，并得到响应**/
        if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        	HttpEntity resEntity = response.getEntity();
			if(resEntity != null){
				result = EntityUtils.toString(resEntity,charset);
			}
        }else{
			throw new Exception("请求失败或者服务器错误");
		}
		return result;  
	}  
}